<?php
/**
 * 阿里云相关服务
 * zhouliang
 * 2020.09.10
 */

namespace App\Services\Tools;

use App\Response\Response;
use Illuminate\Http\Request;
use Alipay\EasySDK\Kernel\Config;
use App\Exceptions\BasicException;
use Alipay\EasySDK\Kernel\Factory;
use Illuminate\Support\Facades\Log;
use AlibabaCloud\Client\AlibabaCloud;
use Alipay\EasySDK\Kernel\Util\ResponseChecker;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;

class AliyunService
{
    public static function authConfig() {
        $options = new Config();
        $options->protocol = 'https';
        $options->gatewayHost = 'openapi.alipay.com';
        $options->signType = 'RSA2';
        $options->appId = env('ALIPAY_APP_ID');
        // 为避免私钥随源码泄露，推荐从文件中读取私钥字符串而不是写入源码中
        $options->merchantPrivateKey = env('ALIPAY_PRIVATE_KEY');
        //注：如果采用非证书模式，则无需赋值上面的三个证书路径，改为赋值如下的支付宝公钥字符串即可
        $options->alipayPublicKey = env('ALIPAY_PUBLIC_KEY');
        Factory::setOptions($options);
    }

    public static function queryAuthResult($certify_id)
    {
        self::authConfig();
        $result = Factory::member()->identification()->query($certify_id);
        $responseChecker = new ResponseChecker();
        if ($responseChecker->success($result) && $result->passed == 'T') {
            return 1;
        }
        return 2;
    }

    public function aliyunAuthMobile($token)
    {
        //先配置在此处,日后整体迁移
        // $access_key =  env('ACCESS_KEY');
        // $access_secret = env('ACCESS_SECRET');
        $access_key =  env('ALI_MOBILE_AUTH_KEY');
        $access_secret = env('ALI_MOBILE_AUTH_SECRET');

        //通信鉴权,频次限定(要了解单次计费是怎么计算法)
        if (empty($token)) throw new BasicException(8001);

        try {
            //设置全局客户端,请求阿里云号码认证服务
            AlibabaCloud::accessKeyClient($access_key, $access_secret)
                ->regionId('cn-hangzhou')
                ->asDefaultClient();

            $result = AlibabaCloud::rpc()
                ->product('Dypnsapi')
                ->scheme('https')
                ->withVersion('2017-05-25')
                ->action('GetMobile')
                ->method('POST')
                ->host('dypnsapi.aliyuncs.com')
                ->options([
                    'query' => [
                        'RegionId' => "cn-hangzhou",
                        'AccessToken' => $token
                    ],
                ])
                ->request();

        } catch (ClientException $e) {
            throw new BasicException(8002, $e->getMessage());

        } catch (ServerException $e) {
            throw new BasicException(8003, $e->getMessage());
        }

        //编写业务逻辑
        $result = $result->toArray();

        if ($result['Code'] != 'OK') {
            throw new BasicException(0, $result['Message']);
        }

        //记录请求日志
        $mobile = isset($result['GetMobileResultDTO']['Mobile']) ? $result['GetMobileResultDTO']['Mobile'] : '';
        if (empty($mobile) || !preg_match("/^1[3-9]\d{9}$/", $mobile)) throw new BasicException(8004);

        return $mobile;
    }
}

